package com.li.controller;

import com.li.common.ModelName;
import com.li.config.AiConfig;
import com.li.dao.RedisChatMemoryStore;
import com.li.utils.IdHandle;
import com.li.utils.IdUtils;
import dev.langchain4j.community.model.dashscope.QwenChatModel;
import dev.langchain4j.community.model.dashscope.QwenStreamingChatModel;
import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.TokenStream;
import dev.langchain4j.service.tool.ToolExecution;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/ai/tools")
public class ChatUseToolsController {

    @Resource
    QwenChatModel qwenChatModel;
    @Resource
    QwenStreamingChatModel qwenStreamingChatModel;
    @Resource
    RedisTemplate<String,String> redisTemplate;
    @Resource
    IdUtils idUtils;
    @Resource
    IdHandle idHandle;
@RequestMapping(value = "/stream/chatMemoryByStream/{id}",produces ="text/stream;charset=UTF-8")
public Flux<String> memoryChatByStream(@PathVariable(name = "id") Integer id, @RequestParam(name = "message") String message)
{

    ChatMemory chatMemory = MessageWindowChatMemory.builder()
            .id(id)
            .maxMessages(30)
            .chatMemoryStore(new RedisChatMemoryStore(redisTemplate,"memoryId", 60 * 60 * 24 *5))
            .build();
    AiConfig.ToolAssistant assistant = AiServices.builder(AiConfig.ToolAssistant.class)
            .chatModel(qwenChatModel)
            .streamingChatModel(qwenStreamingChatModel)
            .chatMemoryProvider(uid -> chatMemory)
            .build();

    String uid = idHandle.uidParse(id, ModelName.QWEN_PLUS_LATEST);
    //获取当前时间
    LocalDateTime now = LocalDateTime.now();
    String str_now = now.toString();
    TokenStream tokenStream = assistant.streamChat(uid, message,str_now);
    return Flux.create(sink -> {
        tokenStream
                .onToolExecuted(System.out::println)  //回调
                .onPartialResponse(sink::next)
                .onCompleteResponse(response -> {sink.complete();})
                .onError(sink::error)
                .start();
    });
}
}
